package win.demonlegion.quartz.job;

import com.alibaba.fastjson.JSON;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import win.demonlegion.util.TimestampUtil;

import java.util.Date;

public abstract class DatetimeTask<T> implements Job {
    private static final Logger logger = LoggerFactory.getLogger(DatetimeTask.class);

    @Autowired
    protected Scheduler scheduler;

    protected JobDataMap jobDataMap;
    protected Date executeDate;

    public DatetimeTask() {}

    public DatetimeTask(T taskData, Date executeDate, String mark) {
        jobDataMap = new JobDataMap();
        setTaskData(taskData);
        setMark(mark);
        this.executeDate = executeDate;
    }

    protected abstract T getTaskData();

    protected void setTaskData(T taskData) {
        jobDataMap.put("taskData", JSON.toJSONString(taskData));
    }

    protected String getMark() {
        return jobDataMap.getString("mark") != null ? jobDataMap.getString("mark") : "";
    }

    protected void setMark(String mark) {
        jobDataMap.put("mark", mark);
    }

    protected abstract void start(Scheduler scheduler);

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        jobDataMap = context.getJobDetail().getJobDataMap();
    }

    protected void addDatetimeJob(Class<? extends Job> jobClass, Date executeDate, Scheduler scheduler) {
        String mark = getMark();
        SimpleScheduleBuilder schedule = SimpleScheduleBuilder.simpleSchedule();
        // 定义Job
        JobDetail job =
                JobBuilder.newJob(jobClass)
                        .withIdentity(mark + "_Datetime", jobClass.getSimpleName())
                        .build();
        job.getJobDataMap().putAll(jobDataMap);
        // 定义Trigger
        Trigger trigger =
                TriggerBuilder.newTrigger()
                        .withIdentity(mark + "_Trigger" + jobClass.getSimpleName() + "_Datetime", jobClass.getSimpleName())
                        .startAt(executeDate)
                        .withSchedule(schedule).build();
        logger.debug("将在" + TimestampUtil.formatDatetime(executeDate) + "执行");
        scheduleDatetimeJob(scheduler, job, trigger);
    }


    protected void scheduleDatetimeJob(Scheduler scheduler, JobDetail job, Trigger trigger) {
        try {
            scheduler.scheduleJob(job, trigger);
        } catch (SchedulerException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }
    }

    protected void deleteDatetimeJob(Class<? extends Job> jobClass, Scheduler scheduler) {
        try {
            scheduler.deleteJob(JobKey.jobKey(getMark() + "_Shunt", jobClass.getSimpleName()));
        } catch (SchedulerException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }
    }
}